package org.example.forum.services.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.dao.ArticleMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Article;
import org.example.forum.model.Board;
import org.example.forum.model.User;
import org.example.forum.services.IArticleService;
import org.example.forum.services.IBoardService;
import org.example.forum.services.IUserService;
import org.example.forum.utils.StringUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private ArticleMapper articleMapper;

    //对用户和板块的操作
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;

    @Override
    public void create(Article article) {
        //参数校验      还有个板块id为null
        if(article== null || article.getUserId() == null
                ||article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle())
                ||StringUtil.isEmpty(article.getContent())) {
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //设置默认值
        article.setState((byte)0);
        article.setDeleteState((byte)0);
        article.setLikeCount(0);
        article.setReplyCount(0);
        article.setVisitCount(0);

        //写入数据库
        int articleRow = articleMapper.insertSelective(article);
        if(articleRow <=0){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));

        }

        //获取板块信息
        Board board = boardService.selectById(article.getBoardId());

        //板块参数校验
        if(board == null){
            //打印日志
            log.info(ResultCode.FAILED_CREATE+",发布帖子失败，board id="+article.getBoardId());

            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));

        }
        //更新板块的数据
        boardService.addOneArticleCountById(board.getId());

        //获取用户信息
        User user =  userService.selectById(article.getUserId()) ;
        //用户参数校验
        if(user == null){
            //打印日志
            log.info(ResultCode.FAILED_CREATE+",发布帖子失败，user id="+article.getUserId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新用户的数据
        userService.addOneArticleCountById(user.getId());
        // 打印日志
        log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");


    }

    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();
        return  articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        if(boardId == null || boardId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Board board = boardService.selectById(boardId);
        //校验板块信息
        if(board == null){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        //参数校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子
        Article article = articleMapper.selectDetailById(id);
        if (article == null) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //更新数据
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
        //写入数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验写入是否合法
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //返回更新的数据
        article.setVisitCount(updateArticle.getVisitCount());

        return article;
    }

    @Override
    public Article selectById(Long id) {
        //参数校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }
    

    @Override
    public Article modify(Long id, String title, String content) {
        //参数校验
        if(id == null || id <=0
                ||StringUtil.isEmpty(title)
                ||StringUtil.isEmpty(content)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子对象
        Article article = articleMapper.selectDetailById(id);
        //帖子不存在
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }


        //创建一个updateArticle对象暂存更新状态
        Article updateArticle = new Article();
        //写入数据
        updateArticle.setId(article.getId());
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        //更新时间
        updateArticle.setUpdateTime(new Date());
        //写入数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验更新
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        return article;
    }

    @Override
    public Article thumbsUpById(Long id) {
        //参数校验
        if(id == null || id <=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子对象
        Article article = articleMapper.selectByPrimaryKey(id);
        //帖子不存在
        if(article == null || article.getDeleteState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //帖子状态异常
        if (article.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //创建一个updateArticle对象暂存更新状态
        Article updateArticle = new Article();
        //写入数据
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount()+1);
        //更新时间
        updateArticle.setUpdateTime(new Date());
        //写入数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验更新
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        return article;
    }

    @Override
    public void addOneReplyCountById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子记录
        Article article = articleMapper.selectByPrimaryKey(id);
        // 校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 帖子已封帖
        if (article.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        // 回复数 = 原回复数 + 1
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());
        // 执行更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //参数校验
        if(userId == null || userId <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userService.selectById(userId);
        if(user == null){
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }


    @Override
    public void deleteById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据Id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 构造一个更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        // 调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        // 更新版块中的帖子数量
        boardService.subOneArticleCountById(article.getBoardId());
        // 更新用户发帖数
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");
    }
}
